using Sunny.UI;
using WinApp.Pages;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using Microsoft.Web.WebView2.WinForms;
using WinApp.Services;

namespace WinApp
{
    public partial class FormMain : UIForm
    {
        private System.Windows.Forms.Timer mouseTrackTimer;
        private PageClickActions pageClickActions;
        private PageOcrActions pageOcrActions;
        private PageAvatars pageAvatars;
        private PageImageMatchActions pageImageMatchActions;
        private PageActionGroups pageActionGroups;
        private PageRunner pageRunner;

        // 添加窗体拖动相关变量
        private bool isDragging = false;
        private Point dragOffset;

        public WebView2 WebView2
        {
            get
            {
                return this.webView21;
            }
        }

        #region 热键相关代码

        // Windows API
        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        // 热键相关常量
        private const uint MOD_CONTROL = 0x0002;
        private const uint VK_1 = 0x31;
        private const uint VK_2 = 0x32;

        // 热键ID枚举
        private enum HotKeyId
        {
            CaptureMousePosition1 = 100,  // Ctrl + 1
            CaptureMousePosition2 = 101,  // Ctrl + 2
            // 在这里添加更多热键ID
            // Action2 = 101,  // 为其他热键预留ID
            // Action3 = 102,
        }

        // 热键注册信息
        private readonly Dictionary<HotKeyId, (uint Modifier, uint Key, string Description)> hotKeyMap = new()
        {
            { HotKeyId.CaptureMousePosition1, (MOD_CONTROL, VK_1, "捕获鼠标位置") },
            { HotKeyId.CaptureMousePosition2, (MOD_CONTROL, VK_2, "捕获鼠标位置") },
            // 在这里添加更多热键映射
            // { HotKeyId.Action2, (MOD_CONTROL, VK_2, "动作2") },
        };

        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;

            if (m.Msg == WM_HOTKEY)
            {
                HotKeyId hotkeyId = (HotKeyId)m.WParam.ToInt32();
                HandleHotkey(hotkeyId);
            }

            base.WndProc(ref m);
        }

        private void HandleHotkey(HotKeyId hotkeyId)
        {
            try
            {
                switch (hotkeyId)
                {
                    case HotKeyId.CaptureMousePosition1:
                        HandleCaptureMousePosition(1);
                        break;
                    case HotKeyId.CaptureMousePosition2:
                        HandleCaptureMousePosition(2);
                        break;
                        // 在这里添加更多热键处理
                        // case HotKeyId.Action2:
                        //     HandleAction2();
                        //     break;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"处理热键时出错: {ex.Message}");
            }
        }

        private void HandleCaptureMousePosition(int pos = 1)
        {
            // 获取鼠标在屏幕上的位置
            Point screenPoint = Cursor.Position;

            // 将屏幕坐标转换为相对于WebView的客户端坐标
            Point clientPoint = webView21.PointToClient(screenPoint);

            // 检查鼠标是否在WebView控件范围内
            if (clientPoint.X >= 0 && clientPoint.X <= webView21.Width &&
                clientPoint.Y >= 0 && clientPoint.Y <= webView21.Height)
            {
                // 获取PageClickActions实例
                if (pageClickActions != null)
                {
                    // 使用坐标值
                    pageClickActions.X = clientPoint.X;
                    pageClickActions.Y = clientPoint.Y;
                }
                if (pos == 1)
                {
                    if (pageOcrActions != null)
                    {
                        pageOcrActions.X1 = clientPoint.X;
                        pageOcrActions.Y1 = clientPoint.Y;
                    }
                    if (pageAvatars != null)
                    {
                        pageAvatars.X1 = clientPoint.X;
                        pageAvatars.Y1 = clientPoint.Y;
                    }
                }
                else
                {
                    if (pageOcrActions != null)
                    {
                        pageOcrActions.X2 = clientPoint.X;
                        pageOcrActions.Y2 = clientPoint.Y;
                    }
                    if (pageAvatars != null)
                    {
                        pageAvatars.X2 = clientPoint.X;
                        pageAvatars.Y2 = clientPoint.Y;
                    }
                }

            }
        }

        private void RegisterHotKeys()
        {
            foreach (var hotkey in hotKeyMap)
            {
                if (!RegisterHotKey(this.Handle, (int)hotkey.Key, hotkey.Value.Modifier, hotkey.Value.Key))
                {
                    this.ShowWarningTip($"热键注册失败：{hotkey.Value.Description}");
                }
            }
        }

        private void UnregisterHotKeys()
        {
            foreach (var hotkey in hotKeyMap)
            {
                UnregisterHotKey(this.Handle, (int)hotkey.Key);
            }
        }

        #endregion

        public FormMain()
        {
            InitializeComponent();

            // 初始化并启动鼠标跟踪定时器
            mouseTrackTimer = new System.Windows.Forms.Timer();
            mouseTrackTimer.Interval = 50; // 50毫秒更新一次
            mouseTrackTimer.Tick += MouseTrackTimer_Tick;
            mouseTrackTimer.Start();

            // 注册所有热键
            RegisterHotKeys();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            // 注销所有热键
            UnregisterHotKeys();

            // 停止定时器
            if (mouseTrackTimer != null)
            {
                mouseTrackTimer.Stop();
                mouseTrackTimer.Dispose();
            }
        }

        private async void FormMain_Load(object sender, EventArgs e)
        {
            pageImageMatchActions = new PageImageMatchActions(webView21);
            pageClickActions = new PageClickActions(webView21);
            pageOcrActions = new PageOcrActions(webView21);
            pageOcrActions.ImageMatchPage = pageImageMatchActions;
            pageAvatars = new PageAvatars(webView21);
            pageAvatars.ImageMatchPage = pageImageMatchActions;
            pageActionGroups = new PageActionGroups(webView21);
            pageRunner = new PageRunner(webView21);
            pageActionGroups.NavBar = uiNavBar1;
            pageActionGroups.Runner = pageRunner;

            uiNavBar1.CreateNode(this.AddPage(pageClickActions));
            uiNavBar1.CreateNode(this.AddPage(pageOcrActions));
            uiNavBar1.CreateNode(this.AddPage(pageAvatars));
            uiNavBar1.CreateNode(this.AddPage(pageImageMatchActions));
            uiNavBar1.CreateNode(this.AddPage(pageActionGroups));
            uiNavBar1.CreateNode(this.AddPage(pageRunner));

            uiNavBar1.SelectedIndex = uiNavBar1.Nodes.Count - 1;

            await webView21.EnsureCoreWebView2Async(null);
            btnLoadGame.PerformClick();
        }

        private void btnLoadGame_Click(object sender, EventArgs e)
        {
            webView21.Source = new Uri("https://warh5.rivergame.net/webgame/index.html?t=14228893");
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void MouseTrackTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                // 获取鼠标在屏幕上的位置
                Point screenPoint = Cursor.Position;

                // 将屏幕坐标转换为相对于WebView的客户端坐标
                Point clientPoint = webView21.PointToClient(screenPoint);

                // 检查鼠标是否在WebView控件范围内
                if (clientPoint.X >= 0 && clientPoint.X <= webView21.Width &&
                    clientPoint.Y >= 0 && clientPoint.Y <= webView21.Height && Width == 1600)
                {
                    uiPanelToolStrip.Text = $"X: {clientPoint.X}, Y: {clientPoint.Y}";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"更新鼠标位置时出错: {ex.Message}");
            }
        }

        private void webView21_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            if (e.IsSuccess)
            {
                //uiPanelTitle.Text = $"[{webView21.CoreWebView2.DocumentTitle}]助手";
            }
        }

        private void btnMinimize_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
        }

        // 添加窗体拖动相关方法
        private void uiPanelTitle_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isDragging = true;
                dragOffset = new Point(e.X, e.Y);
            }
        }

        private void uiPanelTitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                // 获取鼠标在屏幕上的位置
                Point screenPoint = PointToScreen(new Point(e.X, e.Y));


                // 计算窗体新位置（考虑拖动偏移）
                Point newLocation = new Point(
                    screenPoint.X - dragOffset.X,
                    screenPoint.Y - dragOffset.Y
                );

                Screen screen = Screen.FromPoint(screenPoint);

                // 获取桌面工作区域
                Rectangle workingArea = screen.WorkingArea;

                // 检查并修正窗体位置，确保不超出桌面工作区域边界
                if (newLocation.X < workingArea.Left)
                {
                    newLocation.X = workingArea.Left;
                }
                if (newLocation.Y < workingArea.Top)
                {
                    newLocation.Y = workingArea.Top;
                }
                if (newLocation.X + webView21.Width > workingArea.Right)
                {
                    newLocation.X = workingArea.Right - this.Width;
                }
                if (newLocation.Y + this.Height > workingArea.Bottom)
                {
                    newLocation.Y = workingArea.Bottom - this.Height;
                }

                Location = newLocation;
            }
        }

        private void uiPanelTitle_MouseUp(object sender, MouseEventArgs e)
        {
            isDragging = false;
        }

        private void uiPanelTitle_DoubleClick(object sender, EventArgs e)
        {
            Screen screen = Screen.FromControl(uiPanelTitle);
            Rectangle workingArea = screen.WorkingArea;
            int x = workingArea.Right - webView21.Width - 10;
            if (Location.X < x && Location.X != 0)
                Location = new Point(x, 0);
            else if (Location.X == 0)
                Location = new Point((workingArea.Width - Width) / 2, (workingArea.Height - Height) / 2);
            else
                Location = new Point(0, 0);
        }

        private void btnViewRight_Click(object sender, EventArgs e)
        {
            if (Width == 1600)
            {
                Width = 1260;
                uiPanelToolStrip.Text = string.Empty;
                btnViewRight.Symbol = 361524;
            }
            else
            {
                Width = 1600;
                btnViewRight.Symbol = 558090;
            }
        }
    }
}
